#encoding:utf-8
'''
FileName:sharpfsasync.py
Creator:王烨
Date:2010.5.27
'''
from twisted.internet import reactor
from twisted.internet.protocol import ClientCreator
from rpc import ChannelAsync, Proxy
from common_pb2 import *
import auth_pb2
from error import SharpFsError

def ErrorCallback(failure):
        print 'Error:{0}'.format(failure.getErrorMessage())

class SharpFsAsync(object):
    def __init__(self, host, port):
        self.host = host
        self.port = port
        self.creator = ClientCreator(reactor, ChannelAsync)
    
    def Connect(self, callback):
        d = self.creator.connectTCP(self.host, self.port)
        d.addCallback(self.__Connected, callback)
        
    def __Connected(self, p, callback):
        self.channel = p
        self.proxy = Proxy(auth_pb2.Authentication_Stub(p))
        callback()
        
    def Close(self):
        self.channel.Close()
        
    def SetToken(self, token):
        self.token = token
                
    def Login(self, name, password, callback, errback = ErrorCallback):
        def ResultCallback(result):
            if not result.HasField('error'):
                callback(result)
            elif result.error == USER_NOT_EXISTS:
                raise SharpFsError(USER_NOT_EXISTS, "user '{0}' not exists".format(name))
            elif result.error == INCORRECT_PASSWORD:
                raise SharpFsError(INCORRECT_PASSWORD, "Incorrect password")
            else:
                print '未知错误'
        p = auth_pb2.LoginParameters()
        p.name = name
        p.password = password
        d = self.proxy.Authentication.Login(p)
        d.addCallback(ResultCallback)
        d.addErrback(errback)
    
    def Logout(self, callback, errback = ErrorCallback):
        def __Callback(result):
            callback(result)
        p = auth_pb2.LogoutParameters()
        p.token = self.token
        d = self.proxy.Authentication.Logout(p)
        d.addCallback(__Callback)